package com.check.utils;

import javafx.scene.control.Alert;

import java.io.*;
import java.util.Properties;

/**
 * @description:
 * @Author: zyt
 */
public class PropertiesUtils {
    private static Properties properties;
    private static Properties propertiesCache;
    public static Properties getPropertiesValue(String path) {
        if(properties!=null){
            return properties;
        }
        File file = new File(System.getProperties().getProperty("user.dir")+"/config"+path);
        boolean b = file.exists();
        InputStream in = null;
        if(b){
            path = file.getPath();
            try {
                in = new FileInputStream(path);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }else{
            in = PropertiesUtils.class.getClass().getResourceAsStream(path);
        }
        Properties pro = new Properties();
        try (InputStreamReader inputStreamReader = new InputStreamReader(in,"UTF-8")){
            pro.load(inputStreamReader);
        } catch (IOException e) {
            e.printStackTrace();
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("程序异常1003!请截图并联系开发人员!");
            alert.setContentText(e.getMessage());
            alert.showAndWait();
        }
        properties = pro;
        if(!b){
            setPropertiesValue(pro,path);
        }
        return pro;
    }

    public static void setPropertiesValue(Properties properties, String path){
        PropertiesUtils.properties = properties;
        File file = new File(System.getProperties().getProperty("user.dir")+"/config"+path);
        file.getParentFile().mkdirs();
        try(OutputStream outputStream = new FileOutputStream(file)){
            properties.store(outputStream,null);
        }catch (Exception e){
            e.printStackTrace();
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("程序异常1003!请截图并联系开发人员!");
            alert.setContentText(e.getMessage());
            alert.showAndWait();
        }
    }
}
